package sg.edu.nus.dbd.action;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import sg.edu.nus.dbd.biz.DashboardBiz;
import sg.edu.nus.dbd.biz.ConfigurationBiz;
import sg.edu.nus.dbd.formbean.DetailParamData;
import sg.edu.nus.dbd.formbean.ThresholdConfig;
import sg.edu.nus.dbd.util.Constants;
import sg.edu.nus.dbd.util.DateUtil;
import sg.edu.nus.dbd.util.MyLogger;

/**
 * 
 * @author Felix Halim
 * 
 */
public class ODReportsAction extends BaseAction {

	public ActionForward performAction(ActionMapping mapping, ActionForm form,
			HttpServletRequest req, HttpServletResponse res) throws Exception {

		MyLogger.debug(this.getClass(), "execute::Start...");
        int interval = 60;
		try {
			if (req.getParameter("startDate") != null) {
				if (validate(req)) {
					SimpleDateFormat sdf = new SimpleDateFormat(
							"dd/MM/yyyy HH:mm");
					Date startDate = new Date(sdf.parse(
							req.getParameter("startDate")).getTime());
					Date endDate = new Date(sdf.parse(
							req.getParameter("endDate")).getTime());
					interval = Integer.parseInt(req
							.getParameter("interval"));
					String paramName = req.getParameter("paramName");

					MyLogger.debug("Param Name: " + paramName);
					MyLogger.debug("Interval: " + interval);
					MyLogger.debug("Start Date: " + startDate);
					MyLogger.debug("End Date: " + endDate);

					List<DetailParamData> odReportDataList = new DashboardBiz()
							.getODReportData(paramName, interval, DateUtil
									.addMinuteToDate(startDate, -interval),
									endDate);

					ThresholdConfig thConfig = new ConfigurationBiz()
							.getThresholdParameter(paramName);
                    System.out.println(thConfig);
					req
							.setAttribute("warningLevel", thConfig
									.getWarningLevel());
					req.setAttribute("criticalLevel", thConfig
							.getCriticalLevel());
					req.setAttribute("inverse",
							Constants.DASHBOARD_PARAMS_INVERSE.get(paramName));

					req.setAttribute("odReportDataList", odReportDataList);
				}
			}
            req.setAttribute("interval",interval);
			return mapping.findForward("success");
		} catch (Exception e) {
			MyLogger.error(this.getClass(), e);
			return mapping.findForward("error");
		}
	}

	private boolean validate(HttpServletRequest req) {

		String paramName = req.getParameter("paramName");
		String intervalString = req.getParameter("interval");
		String startDateString = req.getParameter("startDate");
		String endDateString = req.getParameter("endDate");

		req.setAttribute("paramName", paramName);
		req.setAttribute("interval", intervalString);
		req.setAttribute("startDate", startDateString);
		req.setAttribute("endDate", endDateString);

		List<String> errorList = new ArrayList<String>();

		if (paramName == null || paramName.trim().length() == 0) {
			errorList.add("Parameter Name is mandatory");
		}
		if (intervalString == null || intervalString.trim().length() == 0) {
			errorList.add("Interval is mandatory");
		} else {
			try {
				int interval = Integer.parseInt(intervalString);
			} catch (Exception e) {
				errorList.add("Interval value is invalid");
			}
		}
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
		if (startDateString == null || startDateString.trim().length() == 0) {
			errorList.add("Start Date is mandatory");
		} else {
			try {
				Date startDate = new Date(sdf.parse(startDateString).getTime());
			} catch (Exception e) {
				errorList.add("Start Date value is invalid");
			}
		}
		if (endDateString == null || endDateString.trim().length() == 0) {
			errorList.add("End Date is mandatory");
		} else {
			try {
				Date endDate = new Date(sdf.parse(endDateString).getTime());
				Date currentDate = new Date(new java.util.Date().getTime());
				if (endDate.after(currentDate))
					errorList.add("End Date should not be after current date");
			} catch (Exception e) {
				errorList.add("End Date value is invalid");
			}
		}
		if (startDateString != null && startDateString.trim().length() > 0
				&& endDateString != null && endDateString.trim().length() > 0) {
			try {
				Date startDate = new Date(sdf.parse(startDateString).getTime());
				Date endDate = new Date(sdf.parse(endDateString).getTime());
				if (startDate.after(endDate))
					errorList.add("Start Date should be before End Date");
			} catch (Exception e) {
				// Ignore this exception as the error message should be been
				// captured if the date format is invalid
			}
		}
		if (errorList.size() > 0) {
			req.setAttribute("errorMessages", errorList);
			return false;
		} else
			return true;
	}
}
